package cn.ranko.framework.core;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhujun on 2016/6/21.
 */
public class ApplicationContextHolder {

    private static Logger logger = Logger.getLogger(ApplicationContextHolder.class);
    private static ApplicationContext rootContext = null;
    private static XmlWebApplicationContext mvcContext = null;
    private static DispatcherServlet dispatcherServlet = null;
    private static Map<String, String> servletMappings;

    public static final void init() throws ServletException {
        if (mvcContext == null) {
            logger.info("Spring container to initialize");
            mvcContext = new XmlWebApplicationContext();
            mvcContext.setConfigLocation("classpath:app-mvc.xml");
            mvcContext.setParent(getRootContext());

            MockServletConfig servletConfig = new MockServletConfig(
                    ApplicationContextHolder.getMvcContext().getServletContext(), "dispatcherServlet");
            dispatcherServlet = new DispatcherServlet(
                    ApplicationContextHolder.getMvcContext());
            dispatcherServlet.init(servletConfig);

            logger.info("Spring container for initial completion");
        }
    }

    private static ApplicationContext getRootContext() {
        if(rootContext==null){
            rootContext = new ClassPathXmlApplicationContext("classpath:app-context.xml");
        }
        return rootContext;
    }

    public static WebApplicationContext getMvcContext() {
        return mvcContext;
    }

    public static DispatcherServlet getDispatcherServlet(){
        return dispatcherServlet;
    }
}
